/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package replic;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import replic.commons.OutputMessage;

/**
 *
 * @author Leonardo Oliveira Moreira
 */
public class RepliCAgentListener extends Thread {
    
    private ServerSocket serverSocket = null;
    private int replicPort;
    
    public RepliCAgentListener(int replicPort) {
        this.replicPort = replicPort;
        OutputMessage.println("RepliC Listener is starting");
        try {
            serverSocket = new ServerSocket(replicPort);
        } catch (IOException ex) {
            OutputMessage.println(ex.getMessage());
            serverSocket = null;
        }
    }

    @Override
    public void run() {
        OutputMessage.println("RepliC Listener is running");
        while (serverSocket != null && !serverSocket.isClosed()) {
            try {
                Socket request = serverSocket.accept();

                OutputMessage.println("Receiving a connection request from " + request.toString());
                
                RepliCAgentListenerThread thread = new RepliCAgentListenerThread(this, request);
                thread.start();
            } catch (IOException ex) {
                OutputMessage.println(ex.getMessage());
            }
        }
    }
    
}